package cn.youyeku.zsxh.api;

import org.json.JSONException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.youyeku.zsxh.Utils.FileUtils;
import cn.youyeku.zsxh.app;
import cn.youyeku.zsxh.ui.home.LoginActivity;
import okhttp3.Callback;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;

/**
 * Created by youye on 17-3-17.
 */

public class AsyncHttpHelp {


    public static final OkHttpClient mOkHttpClient = new OkHttpClient.Builder().cookieJar(new CookiesManager())
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(20, TimeUnit.SECONDS)
            .build();


    public static void get(Request request, Callback responseCallback) {


        mOkHttpClient.newCall(request).enqueue(responseCallback);
    }

    public static void post(Request request, Callback responseCallback) {

        mOkHttpClient.newCall(request).enqueue(responseCallback);
    }


    private static class CookiesManager implements CookieJar {


        @Override
        public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {

            try {
                try {
                    if (!LoginActivity.isLoging && cookies.size() > 0) {
//                        LogUtils.w("写入cookies");
                        FileUtils.writeData(app.getCookiePath(), myCookies.toJson(cookies));
                        app.cookies = cookies;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public List<Cookie> loadForRequest(HttpUrl url) {



            if (!app.isNullCookies() && url.host().equals(XhApi.HOST_BASE)) {
                try {

                    String data = FileUtils.readDataFromSD(app.getCookiePath());
                    List<Cookie> cookie = myCookies.toCoookies(data);
//                    LogUtils.w("请求url" + url.url()+" 方法"+url.toString());
//                    LogUtils.w("读取cookies" + data);

                    return cookie;
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            return new ArrayList<Cookie>();

        }
    }




}
